package org.openCage.artig;

import org.kohsuke.args4j.Option;
import org.openCage.artig.stjx.Module;
import org.openCage.io.fspath.FSPath;
import org.openCage.io.fspath.FSPathBuilder;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;

public class GoMarch implements CmdArgs {


    @Option( name="-p", aliases = {"--project"}, metaVar = "DIR", usage = "the project root, (defaults to current dir)")
    private String dir = ".";


    private FSPath projectDir;

    @Override
    public String getName() {
        return "march";
    }

    @Override
    public void go() {
        projectDir = FSPathBuilder.getPath(new File(dir).getAbsolutePath());

        ArtigLogic al = new ArtigLogic( projectDir );
        al.init();

        // clean
        FSPath buildDir = projectDir.add( "build" );
        deleteDirectory( buildDir.toFile() );

        new AntGen( al ).generate();
        new CalcDeployed( al ).generate();
        new MavenGen( al ).generate();



        for ( Module mod : al.getModules() ) {
            FSPath moduleDir = projectDir.add("build", "modules", mod.getArtifact().getName() );

            if ( !moduleDir.toFile().exists() ) {
                throw new IllegalArgumentException( "no a module or no ant there" );
            }

            try {


                Process process = new ProcessBuilder( "ant" ).
                        directory( moduleDir.toFile()).
                        start();

                InputStream is = process.getInputStream();

                int ch;
                while ( (ch = is.read()) > -1 ) {
                    System.out.write( ch );
                }

            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
            return;

        }


    }

    @Override
    public String usage() {
        return "march";
    }

    static public boolean deleteDirectory(File path) {
        if( path.exists() ) {
            File[] files = path.listFiles();
            for(int i=0; i<files.length; i++) {
                if(files[i].isDirectory()) {
                    deleteDirectory(files[i]);
                }
                else {
                    files[i].delete();
                }
            }
        }
        return( path.delete() );
    }

}
